package com.itheima.d2_xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.ArrayList;
import java.util.List;
/**
 * 将.xml文件数据解析出来，封装成List集合，并比遍历输出
 * */
public class Dom4J {
    public static void main(String[] args)   {
        ArrayList<Book> bookArrayList = new ArrayList<>();//储存所有的解析对象

        SAXReader saxReader = new SAXReader();//Dom4j解析器
        try {
            Document read = saxReader.read("day11properties-xml-log-thread/src/com/" +
                    "itheima/d2_xml/hello.xml");//将xml文件读取到Document对象中

            Element rootElement = read.getRootElement();//获取根元素对象

            List<Element> elements = rootElement.elements();//获取元素下所有子元素

            for (Element element : elements) {
                Book book = new Book();//book对象封装解析数据

                book.setFenlei(element.getName());//分类名

                List<Element> elements1 = element.elements();//次级所有元素

                for (Element element2 : elements1) {
                    book.setBookming(element2.getName());
                    book.setZuoZeName(element2.elementText("name"));
                    book.setPrice(Double.parseDouble(element2.elementText("price")));
                    bookArrayList.add(book);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        bookArrayList.forEach(System.out::println);

    }
}
class Book {
    private String fenlei;
    private String bookming;
    private String zuoZeName;
    private  double price;

    public Book() {
    }

    public String getFenlei() {
        return fenlei;
    }

    public void setFenlei(String fenlei) {
        this.fenlei = fenlei;
    }

    public String getBookming() {
        return bookming;
    }

    public void setBookming(String bookming) {
        this.bookming = bookming;
    }

    public String getZuoZeName() {
        return zuoZeName;
    }

    public void setZuoZeName(String zuoZeName) {
        this.zuoZeName = zuoZeName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "fenlei='" + fenlei + '\'' +
                ", bookming='" + bookming + '\'' +
                ", zuoZeName='" + zuoZeName + '\'' +
                ", price=" + price +
                '}';
    }

    public Book(String fenlei, String bookming, String zuoZeName, double price) {
        this.fenlei = fenlei;
        this.bookming = bookming;
        this.zuoZeName = zuoZeName;
        this.price = price;

    }
}